//
//  JJService.swift
//  swiftStudy
//
//  Created by hamilyjing on 2020/6/24.
//  Copyright © 2020 Alpha. All rights reserved.
//

import Foundation

class JJService {
    var featureset: JJFeatureset?
    
    required init() {
        self.featureset = JJFeatureset()
        self.featureset?.service = self
    }
    
    func needUnloading() -> Bool {
        return false
    }
    
    func willLoad() -> Void {
    }
    
    func didLoad() -> Void {
    }
    
    func willUnload() -> Void {
    }
    
    func didUnload() -> Void {
    }
    
    func actionAfterLogin(_ info_: [AnyHashable : Any]?) -> Void {
    }
    
    func actionAfterLogout(_ info_: [AnyHashable : Any]?) -> Void {
    }
    
    func response(isSuccess isSuccess_: Bool, model model_: Any?, error error_: Error?, request request_: JJRequest) -> Void {
        if isSuccess_ {
            if request_.networkSuccessResponse != nil {
                request_.networkSuccessResponse!(model_, request_.otherInfo)
            }
        } else {
            if request_.networkFailResponse != nil {
                request_.networkFailResponse!(error_, request_.otherInfo)
            }
        }
        
        postResponse(isSuccess: isSuccess_, model: model_, error: error_, request: request_)
    }
    
    func postResponse(isSuccess isSuccess_: Bool, model model_: Any?, error error_: Error?, request request_: JJRequest) -> Void {
        var userInfo = [String: Any]()
        userInfo["isSuccess"] = isSuccess_
        userInfo["identity"] = request_.identity
        userInfo["parameter"] = request_.requestParameters
        userInfo["object"] = model_
        userInfo["error"] = error_
        userInfo["otherInfo"] = request_.otherInfo
        
        let notificationName = request_.identity != nil ? request_.identity! : request_.buildRequestURL()
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: notificationName), object: self, userInfo: userInfo)
    }
}
